package com.dsz.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dsz.po.Admin;
import com.dsz.po.User;
import com.dsz.service.AdminService;

@Controller
public class AdminController {
	// 依赖注入
	@Autowired
	private AdminService adminService;

	// 跳转到后台登录页
	@RequestMapping(value = "toadminlogin.action")
	public String toadminlogin() {
		return "backadmin/login";
	}

	// 登录
	@RequestMapping(value = "adminlogin.action", method = RequestMethod.POST)
	public String adminlogin(String username, String password, Model model, HttpSession session) {
		// 通过账号密码查询用户
		Admin admin = adminService.findAdmin(username, password);
		if (admin != null) {
			// 将对象用户添加到Session
			session.setAttribute("Admin_Session", admin);
			// 测试查看
			System.out.println("登录成功，账号为：" + admin.getUsername());
			// 跳转到主页面
			return "redirect:toadminindex.action";
		}
		model.addAttribute("msg", "账号或密码错误，请重新输入!");
		return "backadmin/login";
	}

	// 跳转到后台主页
	@RequestMapping(value = "toadminindex.action")
	public String toadminindex() {
		return "backadmin/adminindex";

	}

	// 注销登录
	@RequestMapping(value = "adminout.action")
	public String adminout(HttpSession session) {
		// 清除Session
		session.invalidate();
		// 重定向到登录页面
		return "redirect:toadminlogin.action";

	}

	// 跳转到账号管理
	@RequestMapping(value = "toadmin.action")
	public String toadmin(HttpSession session, Model model) {
		// 取值
		Admin admin2 = (Admin) session.getAttribute("Admin_Session");
		Integer id = admin2.getId();
		// 查找
		Admin admin = adminService.findAdminById(id);
		// 传值
		model.addAttribute("admins", admin);

		return "backadmin/admin/admin-list";

	}

	// 跳转到修改账号页面
	@RequestMapping(value = "toupdateadmin.action")
	public String toupdateadmin(HttpSession session, Model model) {
		// 取值
		Admin admin2 = (Admin) session.getAttribute("Admin_Session");
		Integer id = admin2.getId();
		// 查找
		Admin admin = adminService.findAdminById(id);
		// 传值
		model.addAttribute("admins", admin);
		return "backadmin/admin/admin-edit";

	}

	// 修改账户
	@RequestMapping(value = "updateadmin.action")
	public String updateadmin(Admin admin, HttpSession session, Model model) {
		int rows = adminService.updateAdmin(admin);
		if (rows > 0) {
			System.out.println("修改成功");
			return "redirect:toadmin.action";
		}
		System.out.println("修改失败");
		model.addAttribute("msg", "修改失败!");
		return "toupdateadmin.action";

	}

}
